<?php

namespace App\Http\Controllers\Ipad;

use App\Http\Controllers\Controller;
use App\Models\Userdevice;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

class UserdeviceController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->deviceInfo = new Userdevice;
        
    }
    //增加单个关联设备
    public function add(Request $request)
    {   
    	$model = $this->deviceInfo;
        $input = $request->all();
    	$deviceName = $input['deviceName'];
    	$idfa = $input['idfa'];
        $res = $model->where('deviceName',$deviceName)->orwhere('idfa',$idfa)->first();
    	if(!empty($res)){
            $return = ['code'=>500,'msg'=>'该设备已被命名或该命名已被占用!'];
            return response()->json($return);
    	}
    	$model->userId = Auth::id();
        $model->idfa = $idfa;
        $model->deviceName = $deviceName;
        //$model->cmpId = $input['cmpId'];
        $result = $model->save();
        if(!empty($result)){
    		return $this->respond('add_ok',['deviceName'=>$deviceName]);
    	}
    	return $this->respond('add_error');
    }
    //查询单个关联设备
    public function get(Request $request, $id)
    {	
    	$deviceInfo = $this->deviceInfo->find($id);
    	if (empty($deviceInfo)) {
            return $this->respond('get_error');
        }
        $res['id'] = $deviceInfo->id;
        $res['deviceName'] = $deviceInfo->deviceName;
        return $this->respond('get_ok',['deviceInfo'=>$res]);
    }
    //更新单个设备
    public function update(Request $request)
    {
    	$model = $this->deviceInfo;
        $input = $request->input();
        if (empty($input['idfa']) || empty($input['deviceName'])) {
            return $this->respond('empty_error');
        }
        //验证idfa
        $deviceInfo = $model->where('idfa',$input['idfa'])->first();
        if(empty($deviceInfo))
        {
            $return = ['code'=>500,'msg'=>'不存在的设备序列号！'];
            return response()->json($return);
        }
        //验证deviceName
        $deviceName = $input['deviceName'];
    	$res = $model->where('deviceName',$deviceName)->first();
        if(!empty($res) && $res->deviceName != $deviceInfo->deviceName){
            $return = ['code'=>500,'msg'=>'该设备已被命名或该命名已被占用!'];
            return response()->json($return);
        }
        $deviceInfo->deviceName = $deviceName;
        $result = $deviceInfo->save();
        if(!empty($result)){
    		return $this->respond('update_ok',['deviceName'=>$deviceName]);
    	}
    	return $this->respond('update_error');
    }
}
